<?php


	namespace Midi\Util;
	
	class Util {
		
		private function __construct() {}
		
		public static function unpack($byteSequence, $limit = '*') {
			return array_values(unpack('C' . $limit, $byteSequence));
		}
		
		public static function pack($ascii) {
			$packer = new \ReflectionFunction('pack');
			$args   = func_get_args();
			array_unshift($args, 'C*');
			return $packer->invokeArgs($args);
		}
		
		public static function getTicksFromDeltaByteSequence($byteSequence) {
			$bytes = array_reverse(self::unpack($byteSequence));
			$ticks = 0;
			$shift = 0;
			foreach ($bytes as $byte) {
				$ticks |= ($byte & 0x7F) << $shift;
				$shift += 7;
			}
			
			return $ticks;
		}
		
		public static function getDeltaByteSequence($ticks) {
			$byteSequence[] = self::pack($ticks & 0x7F);
			$ticks        >>= 7;
			
			while ($ticks > 0) {
				$byteSequence[] = self::pack(($ticks & 0x7F) | 0x80);
				$ticks >>= 7;
			}
			
			return implode('', array_reverse($byteSequence));
		}
		
		
		
		private static function binaryToHexCallback($value) {
			return str_pad(strtoupper(dechex($value)), 2, '0', STR_PAD_LEFT);
		}
		
		public static function binaryToHex($byteSequence) {
			return array_map('Midi\Util\Util::binaryToHexCallback', self::unpack($byteSequence));
		}
		
	}

?>